{% load static %}
<html>
<head lang="en">
    <title>连板股</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="{% static '/css/jquery-ui.css' %}">
    <link href="{% static '/css/bootstrap.min.css' %}" rel="stylesheet" media="screen">
    <link href="{% static '/css/bootstrap-datetimepicker.min.css' %}" rel="stylesheet" media="screen">
    <script src="{% static '/js/jquery-1.12.4.js' %}"></script>
    <script src="{% static '/js/jquery-ui.js' %}"></script>
    <script type="text/javascript" src="{% static '/js/jquery-1.8.3.min.js' %}" charset="UTF-8"></script>
    <script type="text/javascript" src="{% static '/js/bootstrap.min.js' %}"></script>
    <script type="text/javascript" src="{% static '/js/bootstrap-datetimepicker.js' %}" charset="UTF-8"></script>
    <script type="text/javascript" src="{% static '/js/bootstrap-datetimepicker.zh-CN.js' %}" charset=
            "UTF-8"></script>
</head>
<body>
<div id="FP_chart" style="height: 88.5714%;width: 100.0%;">
    <canvas id="canvas_layer" width="30000" height="800" style="border: 1px solid #eeeeee;">
        您的浏览器不支持
    </canvas>
    <div>
        <div id="indicator"
             style="position: absolute; z-index: 51; border-style: dashed; border-color: rgb(73, 73, 73);left : 10px; top: 20px; border-width: 0px 1px 0px 0px; height: 665px;"/>
    </div>
    <div>
        <div id="float_window"
             style="position: absolute; z-index: 52; padding: 2px; width: 300px; line-height: 16px; font-size: 12px; left: 60px; top: 130px; background-color: rgba(255, 255, 255, 0.9); color: rgb(0, 0, 0); border: 1px solid rgb(0, 0, 0);">
            <canvas id="canv" width="300" height="200" style="border: 1px solid #eeeeee;"></canvas>
        </div>
    </div>
</div>

<div class="container">
    <label class="labe_l">开始日期:</label>
    <div class="clearfix tex_t reset_text">
        　　
        <div class="input-append date fl" style="float:left" id="datetimeStart">
            <input type="text" class="">
            <span class="add-on"><i class="icon-th"></i></span>
        </div>
        <span class="to_link">至</span>
        <div class="input-append date fl" style="float:left" id="datetimeEnd">
            <input type="text" class="">
            <span class="add-on"><i class="icon-th"></i></span>
        </div>
        <input type="number" value="300" id="size">
        <input type="button" value="提交" id="submit_btn"/>
    </div>
</div>

<script>
    var nw = new Date();
    nw.setDate(nw.getDate() - 300);
    //日期插件初始化
    $('#datetimeStart').datetimepicker({
        language: 'zh-CN',
        format: 'yyyy-mm-dd',
        weekStart: 1,
        /*以星期一为一星期开始*/
        todayBtn: 1,
        autoclose: 1,
        minView: 2, initialDate: nw,

        /*精确到天*/
        pickerPosition: "bottom-left"
    }).on("changeDate", function (ev) { //值改变事件
        //选择的日期不能大于第二个日期控件的日期
        if (ev.date) {
            $("#datetimeEnd").datetimepicker('setStartDate', new Date(ev.date.valueOf()));
        } else {
            $("#datetimeEnd").datetimepicker('setStartDate', null);
        }
        console.log(($("#datetimeStart").datetimepicker().val()))
    });
    $('#datetimeEnd').datetimepicker({
        language: 'zh-CN',
        format: 'yyyy-mm-dd',
        weekStart: 1,
        /*以星期一为一星期开始*/
        todayBtn: 1,
        autoclose: 1,
        minView: 2,
        /*精确到天*/
        pickerPosition: "bottom-left"
    }).on("changeDate", function (ev) {
        //选择的日期不能小于第一个日期控件的日期
        if (ev.date) {
            $("#datetimeStart").datetimepicker('setEndDate', new Date(ev.date.valueOf()));
        } else {
            $("#datetimeStart").datetimepicker('setEndDate', new Date());
        }
    });
    //设置默认时间
    $("#datetimeEnd").datetimepicker('setStartDate', new Date());
</script>

</body>
</html>
<script>
    String.prototype.endsWith = function (str) {

        if (str == null || str == "" || this.length == 0 || str.length > this.length) {
            return false;
        }

        if (this.substr(this.length - str.length, this.length) == str) {
            return true;
        } else {
            return false;
        }
        return true;

    };

    var FloatChart = function () {
        this.con = document.getElementById('canv').getContext('2d');
        this.y0 = 20
		this.w = 10
    };
    FloatChart.prototype.drawFont = function (options, vertical) {
        this.con.save();
        this.con.fillStyle = options.color;
        this.con.textAlign = options.textAlign || "center";
        this.con.font = this.w * options.fontSizePercent + "px 宋体";
        this.con.textBaseline = options.textBaseline || "bottom";
        if (vertical) {
            this.con.rotate(-45 * Math.PI / 180);
        }
        this.con.fillText(options.text, options.x, options.y);

        this.con.restore();
    }
    FloatChart.prototype.rectMatrix = function (data, index) {
        // "#ffcc00" , "#ff0000"
        var need_col_s = ["first_high_count", "second_high_count", "third_high_count", "forth_high_count",
            "fifth_high_count"
        ]
        var map_col_en_2_cn = {
            "first_high_count": "一板",
            "second_high_count": "二板",
            "third_high_count": "三板",
            "forth_high_count": "四板",
            "fifth_high_count": "五板"
        }
        var color = ""
        // 找出断层的位置
        // 找到 [1,3]中的第一个0
        var hasFault = false
        var idx = -1
        for (var nck in need_col_s) {
            if (0 == nck) {
                continue;
            }
            var nc = need_col_s[nck];
            var ncv = data[nc][index]
            if (0 == ncv) {
                idx = nck
                break;
            }
        }
        if (idx != -1) {
            // 向后进行遍历
            for (var nck in need_col_s) {
                if (nck <= idx) {
                    continue;
                }
                var ncv = need_col_s[nck]
                if (data[ncv][index] > 0) {
                    hasFault = true
                    break;
                }
            }
        }
        if (hasFault) {
            color = "#ff0000";
        } else {
            color = "#ff9900";
        }

        this.con.fillStyle = color;
        var color_index = 0
        var lineH = 10;
        var base_y = this.y0; //柱形底部位置
        var shift_y = 30;
        var base_x = 60
        var val_shift = 3
        var x = 0;
        x += base_x;
        // width是需要出来的 height是固定的 base_x 固定 Y需要变化
        var y_idx = 0;

        var need_col_sr = ["first_high_count", "second_high_count", "third_high_count", "forth_high_count",
            "fifth_high_count"
        ].reverse()
        for (var nk in need_col_sr) {
            var need_col = need_col_sr[nk]
            var val = data[need_col][index]
            var y = base_y + shift_y * y_idx
            this.con.fillRect(base_x+10, y, val * val_shift, lineH); // startx starty width height
            this.drawFont({
                "text": map_col_en_2_cn[need_col],
                "x": base_x - 40,
                "y": y + lineH,
                "fontSizePercent": 1.7,
                "color": color
            })
            this.drawFont({
                "text": val,
                "x": base_x - 5,
                "y": y + lineH,
                "fontSizePercent": 1.7,
                "color": color
            })
            this.con.fill();
            this.con.restore();
            y_idx++;
        }

    }


    var LChart = function () {
        this.con = document.querySelector("canvas").getContext("2d");
        this.canW = this.con.canvas.width;
        this.canH = this.con.canvas.height;
        this.size = 10;
        this.space = 20;
        this.step = 42;
        this.x0 = this.space;
        this.dateheight = 100
        this.y0 = this.canH - this.space - this.dateheight;
        this.pointSize = 4;
        this.date = document.getElementById('date');
        this.indicator = document.getElementById('indicator');
        this.float_window = document.getElementById('float_window');
        this.tbodys = document.getElementById("tbodys")
        this.gaobiao_scale = 30;
        this.color_index = 0;
    };

    LChart.prototype.check_load_data = function () {
        lc.init();
        lc.monitorMouse();
    };

    LChart.prototype.transform_function_1 = function (data, object) {
        var transform = data * 6 - 2 * object.gaobiao_scale + 300;
        return transform;
    }

    LChart.prototype.transform_function_2 = function (data) {
        var transform = data / 12;
        return transform;
    }

    LChart.prototype.transform_function_3 = function (data) {
        var transform = data / 2;
        return transform;
    }

    LChart.prototype.init = function () {
        // 计算范围
        this.con.clearRect(0, 0, 20000, 1000);

        color_arr = ["#ff0000", "#ffcc00", "#3399ff", "black"]
        // this.huaGeZi();
        this.rectMatrix(data, this.gaobiao_scale);
        this.drawdate(data['date']);
        this.point(persistent_reach_data, this.transform_function_1, "rgb(91,155,213)");
        // 绘制折线的注释
        this.annotation_persistent_reach_data(persistent_reach_data, this.transform_function_1, "black");
        //画出图例
        this.draw_legend()

    };
    LChart.prototype.draw_legend = function () {

        var startX = 40;
        var lineXW = 30;
        var lineY = 60;
        var texts = ["二连板", "三连板", "四连板", "五连板含以上"];
        var interval = 40;

        var XShift = 0;
        var XShiftBase = lineXW * 3
        for (var t in texts) {
            this.drawline(startX + XShift, lineY, startX + XShift + lineXW, lineY, color_arr[t]);
            this.drawFont({
                "text": texts[t],
                "x": startX + XShift + 15,
                "y": lineY,
                "color": "black"
            });
            XShift += XShiftBase;
        }

    }
    LChart.prototype.huaGeZi = function () {
        var lineX = Math.floor(this.canH / this.size);
        for (var i = 1; i < lineX; i++) {
            this.con.beginPath();
            this.con.strokeStyle = "#eee";
            this.con.moveTo(0, i * this.size + 0.5);
            this.con.lineTo(this.canW, i * this.size + 0.5);
            this.con.stroke();
        }
        var lineY = Math.floor(this.canW / this.size);
        for (var j = 1; j < lineY; j++) {
            this.con.beginPath();
            this.con.strokeStyle = "#eee";
            this.con.moveTo(j * this.size + 0.5, 0);
            this.con.lineTo(j * this.size + 0.5, this.canH);
            this.con.stroke();
        }
    };

    LChart.prototype.drawline = function (startX, startY, endX, endY, color) {
        this.con.beginPath();
        //X
        this.con.moveTo(startX, startY);
        this.con.lineTo(endX, endY);
        this.con.strokeStyle = color;
        this.con.stroke();
    };

    LChart.prototype.zb = function () {
        this.con.beginPath();
        //X
        this.con.moveTo(this.x0, this.y0);
        this.con.lineTo(this.canW - this.space, this.y0);
        this.con.lineTo(this.canW - this.space - this.size, this.y0 + this.size / 2);
        this.con.lineTo(this.canW - this.space - this.size, this.y0 - this.size / 2);
        this.con.lineTo(this.canW - this.space, this.y0);
        this.con.fill();
        this.con.strokeStyle = "gray";
        this.con.stroke();
        //Y
        this.con.moveTo(this.x0, this.y0);
        this.con.lineTo(this.x0, this.space);
        this.con.lineTo(this.x0 + this.size / 2, this.space + this.size);
        this.con.lineTo(this.x0 - this.size / 2, this.space + this.size);
        this.con.lineTo(this.x0, this.space);
        this.con.fill();
        this.con.strokeStyle = "gray";
        this.con.stroke();
    };

    LChart.prototype.annotation_persistent_reach_data = function (data, transform_function, color) {
        var that = this
        var topFontColor = 'green'
        var topFontSizePercent = 1 / 25
        for (var i = 0; i < data.length; i++) {
            var canvasX = that.x0 + (i + 1) * this.step - 10;
            var canvasY = that.y0 - transform_function(data[i], this) + 100;
            this.drawFont({
                x: canvasX,
                y: canvasY,
                text: data[i],
                color: topFontColor,
                fontSizePercent: topFontSizePercent
            }, false);
        }
    }
    LChart.prototype.point = function (data, transform_function, color) {
        this.con.beginPath();
        var that = this;
        var prevX = 0;
        var prevY = 0;
        that.con.strokeStyle = color;
        for (var i = 0; i < data.length; i++) {
            var canvasX = that.x0 + (i + 1) * this.step - 20;
            var canvasY = that.y0 - transform_function(data[i], this) + 100;
            that.con.fillRect(canvasX - that.pointSize / 2, canvasY - that.pointSize / 2, that.pointSize, that.pointSize);
            if (i == 0) {
                that.con.moveTo(canvasX, canvasY);
            } else {
                that.con.moveTo(prevX, prevY);
                that.con.lineTo(canvasX, canvasY);
                that.con.stroke();
            }
            prevX = canvasX;
            prevY = canvasY;
        }
    };

    LChart.prototype.fillpoint = function (data, color, startX, startY, transform_function, reverse) {
        var that = this;
        var prevX = startX;
        var prevY = startY;
        that.con.beginPath();
        that.con.strokeStyle = color;
        that.con.fillStyle = color;
        var startx = 0;
        var starty = 0;
        for (var i = 0; i < data.length; i++) { //绘制柱形
            var canvasX = startX + (i + 1) * this.step;
            var offsetY = data[i];
            if (transform_function != null) {
                offsetY = transform_function(data[i]);
            }
            var canvasY = reverse ? startY - offsetY : startY + offsetY;
            if (i == 0) {
                startx = canvasX;
                starty = startY;
                that.con.moveTo(canvasX, canvasY);
            } else {
                that.con.lineTo(canvasX, canvasY);
            }
            prevX = canvasX;
            prevY = canvasY;
        }
        that.con.lineTo(prevX, startY);
        that.con.lineTo(startx, starty);
        //that.con.closePath();
        that.con.fill();
        this.con.restore();
    };


    LChart.prototype.drawRoundRect = function (x, y, width, height, radius, color) {
        this.con.fillStyle = color
        this.con.beginPath();
        this.con.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 3 / 2);
        this.con.lineTo(width - radius + x, y);
        this.con.arc(width - radius + x, radius + y, radius, Math.PI * 3 / 2, Math.PI * 2);
        this.con.lineTo(width + x, height + y - radius);
        this.con.arc(width - radius + x, height - radius + y, radius, 0, Math.PI * 1 / 2);
        this.con.lineTo(radius + x, height + y);
        this.con.arc(radius + x, height - radius + y, radius, Math.PI * 1 / 2, Math.PI);
        this.con.closePath();
    }


    LChart.prototype.drawFont = function (options, vertical) {
        this.con.save();
        this.con.fillStyle = options.color;
        this.con.font = this.w * options.fontSizePercent + "px 宋体";
        this.con.textAlign = options.textAlign || "center";
        this.con.textBaseline = options.textBaseline || "bottom";
        if (vertical) {
            this.con.rotate(-45 * Math.PI / 180);
        }
        this.con.fillText(options.text, options.x, options.y);

        this.con.restore();
    }


    LChart.prototype.rectMatrix = function (data, amplify) {
        var hArrTop = 12; //直方图，柱形上方显示字体
        var pos = 100; //起始位置
        var color_index = 0
        var strokeStyle = "gray"; //柱形颜色
        var topFontColor = "gray"; //柱形顶部文字颜色
        var topFontSizePercent = 1 / 25; //柱形顶部文字大小
        var isShadow = false;

        var lineW = 3; //柱形宽度
        var y = this.y0; //柱形底部位置
        var rectRadiusPercent = 1 / 2; //柱形圆角大小


        if (isShadow) {
            this.con.save();
            this.con.shadowOffsetX = 5; //绘制阴影
            this.con.shadowOffsetY = 5;
            this.con.shadowBlur = 4;
            this.con.shadowColor = "rgba(0, 0, 0, 0.2)";
        }

        this.con.fillStyle = "rgba(0, 0, 0, 0.4)"; //填充柱形,颜色

        var x_base = 1
        var bar_interval = 0
        var bar_interval_base = 10
        var high_base = 0.7

        // for (var i : range()){ for (var k : data){}}
        var rang_ = data['first_high_count'].length

        for (var col_idx = 0; col_idx < rang_; col_idx++) {
            for (var dk in data) {
                if (!dk.endsWith("_high_count") || dk == "first_high_count") { //if not end_with reach
                    continue;
                }

                var val = data[dk][col_idx];
                var color = color_arr[color_index % color_arr.length]
                color_index++;
                var x = this.x0 + 8 * (x_base) + bar_interval;
                this.drawRoundRect(x - lineW / 2, this.y0 - (val * amplify) * high_base, lineW,
                    (val * amplify) * high_base,
                    lineW * rectRadiusPercent, color);
                this.con.fill();
                if (true) {
                    this.drawFont({
                        x: x,
                        y: y - (val * amplify) * high_base,
                        text: val,
                        color: topFontColor,
                        fontSizePercent: topFontSizePercent
                    }, false);
                }
                x_base += 1
            }
            bar_interval += bar_interval_base
        }
        this.con.restore();
    }

    // 画底部的时间
    LChart.prototype.drawdate = function (data) {
        // 需要根据tag_inc.length*date.length 来算 最少要画一个
        var date_length = data.length; //个数
        var lineW = 3; //柱形宽度

        var x_shift_index = 0
        for (var dk in data) {

            var dv = data[dk];
            var x = this.y0 + 100 + this.step * 0.7071 * (x_shift_index - 1)
            this.drawFont({
                x: this.y0 + this.step * 0.7071 * x_shift_index - this.canH * 1.414 - 2 * this.step * this.canH / 200 + 300,
                y: x - 2 * this.step * this.canH / 200 + 120,
                text: dv,
                color: "rgba(0, 0, 0, 0.8)",
                fontSizePercent: 1 / 25
            }, true);
            x_shift_index += 1
        }
        this.con.restore();

    }

    LChart.prototype.updateFloatText = function (ev) {
        var index = 0;
        index = parseInt((ev.layerX - this.x0 + 20) / this.step - 1);
        index = Math.min(index, x_date_length - 1)
        index = Math.max(0, index)

        this.indicator.style = "position: absolute; z-index: 51; border-style: dashed; border-color: rgb(73, 73, 73);left: " +
            (this.x0 + (index + 1) * this.step - 20) +
            "px; top: 20px; border-width: 0px 1px 0px 0px; height: " + ((this.canH - 135) + "") + "px;";

        // 需要转为data对应的index 前面的累加和s 后面的累加和e 对于数据 1 2 3 有 s0 0 e0 1  s2 1 e2 3
        var s = 0
        var e = 0

        // 清除画布
        fct.con.clearRect(0, 0, 30000, 30000)
        //

        fct.rectMatrix(data, index)
        if (this.float_window.offsetLeft != (60 + ev.layerX - ev.clientX)) {
            this.float_window.style =
                "position: absolute; z-index: 52; padding: 2px; width: 300px; line-height: 16px;\
             font-size: 12px; left: " +
                ((60 + ev.layerX - ev.clientX) + "") +
                "px; top: 80px; background-color: rgba(255, 255, 255, 0.9); color: rgb(0, 0, 0);\
              border: 1px solid rgb(0, 0, 0);"
        }

        if (ev.layerX < (ev.layerX - ev.clientX + 280) && this.float_window.offsetLeft == (60 + ev.layerX - ev.clientX)) {
            this.float_window.style =
                "position: absolute; z-index: 52; padding: 2px; width: 300px; line-height: 16px;\
             font-size: 12px; left: " +
                ((310 + ev.layerX - ev.clientX) + "") +
                "px; top: 80px; background-color: rgba(255, 255, 255, 0.9); color: rgb(0, 0, 0);\
              border: 1px solid rgb(0, 0, 0);"
        } else if (ev.layerX > (ev.layerX - ev.clientX + 280) && this.float_window.offsetLeft == (310 + ev.layerX - ev.clientX)) {
            this.float_window.style =
                "position: absolute; z-index: 52; padding: 2px; width: 300px; line-height: 16px;\
             font-size: 12px; left: " +
                ((60 + ev.layerX - ev.clientX) + "") +
                "px; top: 80px; background-color: rgba(255, 255, 255, 0.9); color: rgb(0, 0, 0);\
              border: 1px solid rgb(0, 0, 0);"
        }
    }


    LChart.prototype.monitorMouse = function () {
        that = this;
        var d = document.getElementById('canvas_layer');
        d.addEventListener('mouseenter', function () {
            that.float_window.style.display = "";
            that.indicator.style.display = "";
        })
        d.addEventListener('mousemove', function (ev) {
            ev = ev || window.event;
            that.updateFloatText(ev);
        })
        d.addEventListener('mouseleave', function (ev) {
            if (ev.relatedTarget != that.indicator) {
                that.float_window.style.display = "none";
                that.indicator.style.display = "none";
            }
        })
        d.addEventListener('mouseover', function (ev) {
            //ev = ev || window.event;
            //that.updateFloatText(ev);
        })
        d.addEventListener('mouseout', function (ev) {
            if (ev.relatedTarget != that.indicator) {
                that.float_window.style.display = "none";
                that.indicator.style.display = "none";
            }
        })
    }

    var lc = new LChart();
    var fct = new FloatChart();
    var send_default_parse_2_backend = function () {
        var market_thermometer = new XMLHttpRequest();
        market_thermometer.overrideMimeType("application/json");
        market_thermometer.open("GET", "/api/high-limit", true);
        // market_thermometer.open("GET", "MarketThermometer.json", true);
        market_thermometer.send(null);
        market_thermometer.onreadystatechange = function () {
            if (market_thermometer.readyState == 4 && market_thermometer.status == 200) {
                all_data = JSON.parse(market_thermometer.responseText);
                // cengzhang_earning_data = data['cengzhang_earning'];
                // zhangting_earning_data = data['zhangting_earning'];
                parse_data(all_data)
            }
        }
    }

    parse_data = function (all_data) {
        data = all_data;
        if (all_data['api_call'] == 1) {
            persistent_reach_data = Array()
            persistent_reach_data = data["continue_high_ratio"];

            x_date_length = data['date'].length
            // date_list_a = data['date'];
            // cengzhang_list = data['cengzhang'];
            // zhangting_list = data['zhangting'];
            // diechao_5 = data['diechao_5'];
            // dieting_list = data['dieting'];
            // 计算出x轴上一个会出现多少个日期，及时今天没有爆发的标签，也需要进行操作

            lc.gaobiao_scale = data['gaobiao_scale'];
            lc.check_load_data();
        } else {
            alert(all_data['message'])
        }
    }
    $(document).ready(function () {
        const Url = "api/high-limit";
        $('#submit_btn').click(function () {
            var jsoStr = {
                "datetimeStart": $("#datetimeStart").children("input")[0].value,
                "datetimeEnd": $("#datetimeEnd").children("input")[0].value,
                "size": $("#size").value
            };
            $.ajax({
                url: Url,
                type: "POST",
                data: jsoStr,
                success: function (result) {
                    console.log(result);
                    parse_data(result)
                },
                error: function (error) {
                    console.log(error)
                    parse_data(error)
                }
            })
        })
    });
    send_default_parse_2_backend();
</script>
